package com.msb.monitor.task;

import com.msb.common.constart.CacheConstant;
import com.msb.common.constart.RabbitMQConstants;
import com.msb.monitor.feign.CacheClient;
import com.msb.monitor.util.MailUtil;
import com.rabbitmq.client.Channel;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.IOException;
import java.util.Set;

/**
 * @Author: lmf
 * @Create: 2025/3/24 14:51
 * @module
 */
@Component
@Slf4j
public class MonitorQueueMessageCountTask {
    String text = "<h1>您的队列消息队列堆积了，队名为%s，消息个数为%s</h1>";

    // 注入RabbitMQ的ConnectionFactory
    @Resource
    private ConnectionFactory connectionFactory;

    @Resource
    private CacheClient cacheClient;

    @Resource
    private MailUtil mailUtil;

    @XxlJob("monitorQueueMessageCount")
    public void monitorQueueMessageCount() {

        // 获取redis所有队列名称
        // 查询队列名称的固定pattern
        String QUEUE_PATTERN = CacheConstant.CHANNEL + "*";
        Set<String> keys = cacheClient.keys(QUEUE_PATTERN);

        //2、需要基于channel去操作
        Connection connection = connectionFactory.createConnection();
        Channel channel = connection.createChannel(false);
        listenQueueAndSendEmail(channel, RabbitMQConstants.SMS_PRE_SEND);

        for (String key : keys) {
            String queueName = RabbitMQConstants.SMS_GATEWAY + key.substring(CacheConstant.CHANNEL.length());
            listenQueueAndSendEmail(channel, queueName);
        }
    }

    private void listenQueueAndSendEmail(Channel channel, String queueName) {
        try {
            channel.queueDeclare(queueName, true, false, false, null);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //3、拿到对应队列的消息，确认消息数量，超过限制，及时通知
        long count = 0;

        try {
            long messageCount = channel.messageCount(queueName);
            // 队列消息限制
            long MESSAGE_COUNT_LIMIT = 0;
            if (messageCount > MESSAGE_COUNT_LIMIT) {
                mailUtil.sendEmail(queueName + "队列消息堆积", String.format(text,
                        queueName, messageCount));
            }
        } catch (IOException | MessagingException e) {
            e.printStackTrace();
        }
    }


}
